<template>
  <view class="repair-request">
    <!-- 家电类型选择 -->
    <view class="repair-type">
      <view class="section-title">家电类型</view>
      <view class="type-options">
        <view 
          v-for="type in applianceTypes" 
          :key="type.value"
          :class="['type-item', selectedType === type.value ? 'active' : '']"
          @tap="selectType(type.value)"
        >
          <text>{{ type.label }}</text>
        </view>
      </view>
    </view>
    
    <!-- 安装位置 -->
    <view class="repair-location">
      <view class="section-title">安装位置</view>
      <view class="location-select" @tap="showLocationSelect">
        <text>{{ selectedLocation || '请选择安装位置' }}</text>
        <text class="arrow">></text>
      </view>
    </view>
    
    <!-- 安装需求说明 -->
    <view class="repair-description">
      <view class="section-title">安装需求说明</view>
      <textarea 
        class="description-input" 
        placeholder="请详细描述您的安装需求，如：是否需要打孔、特殊安装要求等" 
        v-model="description"
        maxlength="200"
      ></textarea>
      <view class="word-count">{{ description.length }}/200</view>
    </view>
    
    <!-- 图片上传 -->
    <view class="repair-images">
      <view class="section-title">问题图片（选填）</view>
      <view class="image-upload">
        <view 
          class="image-item" 
          v-for="(image, index) in images" 
          :key="index"
        >
          <image :src="image" mode="aspectFill"></image>
          <view class="delete-icon" @tap="deleteImage(index)">×</view>
        </view>
        <view class="upload-button" @tap="chooseImage" v-if="images.length < 3">
          <text class="plus">+</text>
          <text class="upload-text">上传图片</text>
        </view>
      </view>
      <view class="upload-tip">最多上传3张图片，每张不超过5MB</view>
    </view>
    
    <!-- 联系方式 -->
    <view class="contact-info">
      <view class="section-title">联系方式</view>
      <view class="input-group">
        <view class="input-item">
          <text class="label">联系人</text>
          <input type="text" v-model="contactName" placeholder="请输入联系人姓名" />
        </view>
        <view class="input-item">
          <text class="label">手机号码</text>
          <input type="number" v-model="contactPhone" placeholder="请输入联系电话" maxlength="11" />
        </view>
        <view class="input-item">
          <text class="label">预约时间</text>
          <picker 
            mode="date" 
            :value="appointmentDate" 
            :start="startDate" 
            :end="endDate" 
            @change="onDateChange"
          >
            <view class="picker-value">{{ appointmentDate || '请选择预约日期' }}</view>
          </picker>
        </view>
      </view>
    </view>
    
    <!-- 提交按钮 -->
    <view class="button-group">
      <button 
        class="submit-button" 
        @tap="submitRepairRequest" 
        :disabled="!isFormValid"
      >
        提交安装申请
      </button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    const today = new Date()
    const startDate = today.toISOString().split('T')[0]
    
    const endDate = new Date(today)
    endDate.setDate(today.getDate() + 30)
    
    return {
      applianceTypes: [
        { value: 'airconditioner', label: '空调' },
        { value: 'waterheater', label: '热水器' },
        { value: 'washer', label: '洗衣机' },
        { value: 'tv', label: '电视机' },
        { value: 'other', label: '其他' }
      ],
      selectedType: '',
      selectedLocation: '',
      description: '',
      images: [],
      contactName: '',
      contactPhone: '',
      appointmentDate: '',
      startDate: startDate,
      endDate: endDate.toISOString().split('T')[0],
      loading: false
    }
  },
  computed: {
    isFormValid() {
      return this.selectedType && 
             this.selectedLocation && 
             this.description && 
             this.contactName && 
             this.contactPhone && 
             this.appointmentDate
    }
  },
  onLoad() {
    // 获取用户信息，自动填充联系方式
    this.getUserInfo()
  },
  methods: {
    selectType(type) {
      this.selectedType = type
    },
    showLocationSelect() {
      const locations = ['客厅', '主卧', '次卧', '厨房', '卫生间', '阳台', '其他']
      
      uni.showActionSheet({
        itemList: locations,
        success: (res) => {
          this.selectedLocation = locations[res.tapIndex]
        }
      })
    },
    chooseImage() {
      uni.chooseImage({
        count: 3 - this.images.length,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          // 检查图片大小
          const validImages = res.tempFilePaths.filter((path, index) => {
            return res.tempFiles[index].size <= 5 * 1024 * 1024 // 5MB
          })
          
          if (validImages.length < res.tempFilePaths.length) {
            uni.showToast({
              title: '部分图片超过5MB，已过滤',
              icon: 'none'
            })
          }
          
          this.images = [...this.images, ...validImages]
        }
      })
    },
    deleteImage(index) {
      this.images.splice(index, 1)
    },
    onDateChange(e) {
      this.appointmentDate = e.detail.value
    },
    getUserInfo() {
      try {
        const userInfo = uni.getStorageSync('userInfo')
        if (userInfo) {
          const user = JSON.parse(userInfo)
          this.contactName = user.name || ''
          this.contactPhone = user.phone || ''
        }
      } catch (e) {
        console.error('获取用户信息失败', e)
      }
    },
    async submitRepairRequest() {
      if (this.loading) return
      this.loading = true
      
      try {
        const uploadedImages = await this.uploadImages()
        
        // 提交安装申请
        const res = await this.$api.submitInstallationRequest({
          type: this.selectedType,
          location: this.selectedLocation,
          description: this.description,
          images: uploadedImages,
          contactName: this.contactName,
          contactPhone: this.contactPhone,
          appointmentDate: this.appointmentDate
        })
        
        uni.showToast({
          title: '提交成功',
          icon: 'success'
        })
        
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
      } catch (error) {
        console.error('提交安装申请失败', error)
        uni.showToast({
          title: '提交失败，请重试',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    async uploadImages() {
      if (this.images.length === 0) return []
      
      const uploadPromises = this.images.map(image => {
        return new Promise((resolve, reject) => {
          uni.uploadFile({
            url: this.$api.baseUrl + '/upload',
            filePath: image,
            name: 'file',
            success: (res) => {
              const data = JSON.parse(res.data)
              resolve(data.url)
            },
            fail: (err) => {
              reject(err)
            }
          })
        })
      })
      
      try {
        return await Promise.all(uploadPromises)
      } catch (error) {
        console.error('上传图片失败', error)
        throw new Error('上传图片失败')
      }
    }
  }
}
</script>

<style lang="scss">
.repair-request {
  padding: 20rpx;
  background: #f5f5f5;
  min-height: 100vh;
}

.repair-type, .repair-location, .repair-description, .repair-images, .contact-info {
  background: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(106, 17, 203, 0.1);
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
  color: #6a11cb;
}

.type-options {
  display: flex;
  flex-wrap: wrap;
  
  .type-item {
    width: 30%;
    margin: 0 1.2% 20rpx;
    padding: 20rpx 0;
    text-align: center;
    border: 1px solid #ddd;
    border-radius: 8rpx;
    transition: all 0.3s ease;
    
    &.active {
      border-color: #6a11cb;
      color: #6a11cb;
      background-color: rgba(106, 17, 203, 0.05);
    }
  }
}

.location-select {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1px solid #eee;
}

.description-input {
  width: 100%;
  height: 200rpx;
  padding: 20rpx;
  border: 1px solid #eee;
  border-radius: 8rpx;
  box-sizing: border-box;
  font-size: 28rpx;
}

.word-count {
  text-align: right;
  font-size: 24rpx;
  color: #999;
  margin-top: 10rpx;
}

.image-upload {
  display: flex;
  flex-wrap: wrap;
  
  .image-item, .upload-button {
    width: 200rpx;
    height: 200rpx;
    margin-right: 20rpx;
    margin-bottom: 20rpx;
    border-radius: 8rpx;
    overflow: hidden;
    position: relative;
  }
  
  .image-item {
    image {
      width: 100%;
      height: 100%;
    }
    
    .delete-icon {
      position: absolute;
      top: 0;
      right: 0;
      width: 40rpx;
      height: 40rpx;
      background: rgba(0, 0, 0, 0.5);
      color: #fff;
      text-align: center;
      line-height: 40rpx;
      font-size: 32rpx;
    }
  }
  
  .upload-button {
    border: 1px dashed #ddd;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    
    .plus {
      font-size: 60rpx;
      color: #999;
      line-height: 1;
      margin-bottom: 10rpx;
    }
    
    .upload-text {
      font-size: 24rpx;
      color: #999;
    }
  }
}

.upload-tip {
  font-size: 24rpx;
  color: #999;
  margin-top: 10rpx;
}

.input-group {
  .input-item {
    display: flex;
    align-items: center;
    padding: 20rpx 0;
    border-bottom: 1px solid #eee;
    
    .label {
      width: 160rpx;
      font-size: 28rpx;
      color: #333;
    }
    
    input, .picker-value {
      flex: 1;
      font-size: 28rpx;
    }
    
    .picker-value {
      color: #333;
      
      &:empty::before {
        content: '请选择预约日期';
        color: #999;
      }
    }
  }
}

.button-group {
  padding: 0 20rpx;
  margin: 40rpx 0 120rpx;
  position: relative;
}

.submit-button {
  width: 100%;
  height: 90rpx;
  line-height: 90rpx;
  background: linear-gradient(135deg, #6a11cb 0%, #8e44ad 100%);
  color: #fff !important;
  border-radius: 45rpx;
  text-align: center;
  font-size: 32rpx;
  font-weight: bold;
  letter-spacing: 2rpx;
  box-shadow: 0 8rpx 20rpx rgba(106, 17, 203, 0.3);
  transition: all 0.3s ease;
  border: none;
  position: relative;
  overflow: hidden;
  
  &::after {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: linear-gradient(rgba(255, 255, 255, 0.2), rgba(255, 255, 255, 0));
    opacity: 0;
    transition: opacity 0.3s;
  }
  
  &:active::after {
    opacity: 1;
  }
  
  &:disabled {
    background: #cccccc;
    box-shadow: none;
    color: #ffffff;
  }
  
  &:active {
    transform: translateY(3rpx);
    box-shadow: 0 4rpx 10rpx rgba(106, 17, 203, 0.2);
  }
}

.arrow {
  color: #6a11cb;
}
</style>
